package com.leesche.zcsp.node.web.controller.web.v2.promocode;

import com.leesche.zcsp.node.utils.PropKit;
import com.leesche.zcsp.node.utils.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.model.PubDeviceBalanceExport;
import com.leesche.zcsp.node.web.model.PubDiscountCode;
import com.leesche.zcsp.node.web.service.PubDeviceBalanceExportService;
import com.leesche.zcsp.node.web.service.PubDiscountCodeService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDiscountCodeDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDiscountCodeCondition;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.leesche.zcsp.node.utils.CsvUtil.createCsvFile;
import static com.leesche.zcsp.node.utils.UtilDate.dateToStr;
import static com.leesche.zcsp.node.utils.UtilDate.timeToStr;
import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

/**
 * @author reid
 * @Created 16/12/20
 */
@Controller
@RequestMapping("/v2/promocode")
public class WebPromoCodeController extends WebAdminController {
    private final static Logger LOGGER = LoggerFactory.getLogger(WebPromoCodeController.class);

    private static final String SHOW_VIEW = "web/v2/promocode/showView";
    private static final String ADD_VIEW = "web/v2/promocode/addView";

    private static String path = PropKit.use("rqcode.properties").get("destExportPath");

    @Autowired
    private PubDiscountCodeService codeService;
    @Autowired
    private PubDeviceBalanceExportService exportService;

    @RequestMapping("/showView")
    public String showView(Model model) {
        Long adminId = getAdminId();
        QueryPubDiscountCodeCondition condition = new QueryPubDiscountCodeCondition();
        condition.setAdminId(adminId);
        List<PubDiscountCodeDto> list = codeService.findListsByCondition(condition);

        List<PubDiscountCodeDto> unusedList = new ArrayList<PubDiscountCodeDto>();
        List<PubDiscountCodeDto> usedList = new ArrayList<PubDiscountCodeDto>();
        List<PubDiscountCodeDto> outList = new ArrayList<PubDiscountCodeDto>();
        Date now = new Date();
        for (PubDiscountCodeDto dto : list) {
            if (dto.getCodestate() == 2) {
                usedList.add(dto);//已使用
            } else if (dto.getCodestate() == 1 && dto.getOutTime().after(now)) {
                unusedList.add(dto);//未使用
            } else if (dto.getCodestate() == 3 || dto.getOutTime().before(now)) {
                outList.add(dto);//已过期
            }
        }

        model.addAttribute("unusedList", unusedList);
        model.addAttribute("usedList", usedList);
        model.addAttribute("outList", outList);
        return SHOW_VIEW;
    }

    @RequestMapping("/addView")
    public String addView() {
        return ADD_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> addCoupon(Integer coin, String startDate, String endDate, Integer count) {
        Long adminId = getAdminId();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (count > 1) {
                List<PubDiscountCode> list = new ArrayList<PubDiscountCode>();
                for (int i = 0; i < count; i++) {
                    PubDiscountCode coupon = new PubDiscountCode();
                    coupon.setAdminid(adminId);
                    coupon.setCoin(coin);
                    coupon.setCodestate(1);
                    coupon.setDiscountcode(UUIDGenerateUtil.generateShortUuid());
                    coupon.setIntime(sdf.parse(startDate + " 00:00:00"));
                    coupon.setOuttime(sdf.parse(endDate + " 23:59:59"));
                    coupon.setCreatetime(now);
                    coupon.setUpdatetime(now);
                    list.add(coupon);
                }
                codeService.insertBatch(list);
            } else {
                PubDiscountCode coupon = new PubDiscountCode();
                coupon.setAdminid(adminId);
                coupon.setCoin(coin);
                coupon.setCodestate(1);
                coupon.setDiscountcode(UUIDGenerateUtil.generateShortUuid());
                coupon.setIntime(sdf.parse(startDate + " 00:00:00"));
                coupon.setOuttime(sdf.parse(endDate + " 23:59:59"));
                coupon.setCreatetime(now);
                coupon.setUpdatetime(now);
                codeService.insert(coupon);
            }
        } catch (ParseException e) {
            LOGGER.error("日期格式转换错误,", e.getMessage());
            return WebResult.failure(e).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return WebResult.failure(e).toMap();
        }

        return WebResult.success().toMap();
    }

    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public Map<String, Object> export(
        QueryPubDiscountCodeCondition condition
    ){
        try {
            Long adminId = getAdminId();
            Long exportId=0L;
            condition.setAdminId(adminId);
            condition.setCodeState(1);
            condition.setSDate(timeToStr(new Date()));
            List<PubDiscountCodeDto> codeDtoList = codeService.findListsByCondition(condition);
            if(codeDtoList.size()!=0){
                List<Map<String,Object>> exportData = new ArrayList<Map<String,Object>>();
                for(PubDiscountCodeDto dto : codeDtoList){
                    Map<String,Object> row = new LinkedHashMap<String,Object>();
                    row.put("title", dto.getDiscountcode());
                    row.put("content", dto.getCoin());
                    row.put("stime", dateToStr(dto.getInTime()));
                    row.put("etime", dateToStr(dto.getOutTime()));
                    exportData.add(row);
                }

                LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("title", "优惠码");
                map.put("content", "币数");
                map.put("stime", "有效期开始时间");
                map.put("etime", "有效期结束时间");

                File file = createCsvFile(exportData,map,path,"LXJ-");
                if(file.exists() == false){
                    return WebResult.failure("生成失败!").toMap();
                }else{
                    //添加用户导出记录
                    PubDeviceBalanceExport balanceExport = new PubDeviceBalanceExport();
                    balanceExport.setUserId(adminId);
                    balanceExport.setPathUrl(file.getPath());
                    balanceExport.setExportName(file.getName());
                    balanceExport.setState(1);
                    balanceExport.setExportType(1);
                    balanceExport.setCreateTime(new Date());
                    exportService.insert(balanceExport);
                    exportId = balanceExport.getExportId();
                }
            }else{
                return WebResult.failure("暂无数据!").toMap();
            }
            return WebResult.success().put("exportId",exportId).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 导出下载
     * @return
     */
    @RequestMapping(value = "/exportDown/{exportId}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@PathVariable("exportId")Long exportId) throws IOException {
        PubDeviceBalanceExport export = exportService.selectByPrimaryKey(exportId);
        File file = new File(path+export.getExportName());
        String dfileName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        headers.setContentDispositionFormData("attachment", dfileName);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

}
